package cn.kgc.ssm.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.kgc.ssm.dto.QueryTemplate;
import cn.kgc.ssm.entity.Template;
import cn.kgc.ssm.mapper.TemplateMapper;
import cn.kgc.ssm.service.TemplateService;
import cn.kgc.ssm.util.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @author 课工场
 * @date 2023/10/26
 * @description
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateMapper templateMapper;


    @Override
    public ResponseResult getPageDate(QueryTemplate queryTemplate) {

        PageHelper.startPage(queryTemplate.getPage(),queryTemplate.getLimit());
        List<Template>  templates =  templateMapper.getList(queryTemplate.getFileName());
        PageInfo<Template> templatePageInfo = new PageInfo<>(templates);

        // 获取数据总条数
        long total = templatePageInfo.getTotal();
        List<Template> list = templatePageInfo.getList();

        return ResponseResult.success(list,total);
    }

    @Override
    public ResponseResult upload(MultipartFile file)  {

        //  1.判定文件是否为空
        if (file.isEmpty()){
            throw  new RuntimeException("文件不能为空");
        }

        // 2.获取文件信息  文件名
        String originalFilename = file.getOriginalFilename();     // 学生信息模板.xls

        byte[] bytes = new byte[0];   // 解决文件名中文乱码问题
        try {
            bytes = originalFilename.getBytes("ISO8859-1");
            originalFilename  = new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        System.out.println("originalFilename = " + originalFilename);
        double size = file.getSize()/1024;

        String uuid = IdUtil.simpleUUID();   // 文件在服务器中存储的唯一标识符
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);  //  xls
        String lastName = uuid+"."+filenameExtension;


        originalFilename =  StringUtils.stripFilenameExtension(originalFilename);
        // 3. 文件上传
        File f = new File("D:\\upload\\" + lastName);

        try {

            file.transferTo(f);
            //将文件的基本信息写入数据库

            Template template = new Template();
            template.setSize(size);
            template.setFileName(originalFilename);
            template.setUuidName(lastName);
            template.setCreateTime(new Date());

            templateMapper.addTemplate(template);

        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }


        return ResponseResult.success();
    }
}
